<?php

namespace app\company\model;


use app\admin\model\Goods;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

/**
 *  盘点单
 * @property int $id
 * @property string $no
 * @property int $start_time
 * @property string $goods_cate_name
 * @property int $end_time
 * @property int $stock_status 盘点状态:1:未盘点,2:盘点中,3:审核中,4:盘点结束,5:已驳回',
 * @property int $status 状态:1:启用,0:禁用',
 * @property int $create_time
 * @property int $update_time
 * @property int $delete_time
 * @property int $company_id 公司ID
 * @property int $warehouse_id 仓库ID
 * @property int $goods_cate_id 商品分类ID
 * @property int $operator_id 提交人ID
 * @property int $auditor_id 审核人ID
 * @property int $creator_id 创建人ID
 * @property int $auditor_time 审核时间
 */
class WarehouseTakeStock extends Base
{


    /**
     * 盘点单创建前
     * @param WarehouseTakeStock $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function onBeforeInsert(WarehouseTakeStock $model): void
    {
        $model->no         = "PD" . date("Ymd") . rand(10000, 99999);
        $model->start_time = time();
        if ($model['type'] == 2) {
            $model->goods_cate_name = getGoodsCateName(request()->param('goods_cate_id', 0));//更新分类名称
        }


    }

    public static function onAfterInsert(WarehouseTakeStock $model): void
    {
        $param = request()->param();
        //全盘
        $sql = CompanyOrderStorage::warehouseId($model->warehouse_id)->where('quantity', '>', 0);
        //分类盘
        if ($model['type'] == 2) {
            //查找所有的商品规格
            $goods_cate_ids = getGoodsCateIds($model->goods_cate_id);//一级分类或二级分类都可以创建,如果是一级分类,转化为具体的二级分类
            $goodsIds       = Goods::whereIn('goods_cate_id', $goods_cate_ids)->column('id');
            $sql            = $sql->whereIn('goods_id', $goodsIds);
        }
        $list = $sql->select();
        if ($list->isEmpty()) exception("没有可盘点的数据");
        $list = $list->toArray();
        $add  = [];
        foreach ($list as $item) {
            $array['company_id']               = $item['company_id'];
            $array['supplier_id']              = $item['supplier_id'];
            $array['warehouse_id']             = $item['warehouse_id'];
            $array['warehouse_storage_id']     = $item['warehouse_storage_id'];
            $array['goods_id']                 = $item['goods_id'];
            $array['goods_rule_id']            = $item['goods_rule_id'];
            $array['warehouse_take_stock_id']  = $model->id;
            $array['company_order_storage_id'] = $item['id'];
            $array['quantity']                 = $item['quantity'];
            $array['origin_quantity']          = $item['quantity'];
            $add[]                             = $array;
        }
        (new WarehouseTakeStockGoods())->saveAll($add);
    }

    /**
     * 盘点单更新前
     * @param WarehouseTakeStock $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeUpdate(WarehouseTakeStock $model): void
    {
        $param = request()->param();

        //提交审核
        if ($model->stock_status == 2 && $model->getOrigin('stock_status') != 1) exception("盘点单状态异常,无法提交审核");
        if ($model->stock_status == 2) {
            $model->operator_id = getCompanyUserId();//盘点人
            $model->end_time    = time();//盘点结束时间
        }
        //审核通过
        if ($model->stock_status == 3 && $model->getOrigin('stock_status') != 2) exception("盘点单状态异常,无法审核通过");
        if ($model->stock_status == 3) {
            $model->auditor_id   = getCompanyUserId();//审核人
            $model->auditor_time = time();//审核时间
            //找出所有被更改的数据
            $model->warehouseTakeStockGoodss()->where('is_modify', 2)->select()->each(function ($item) {
                //修改库存
                $item->companyOrderStorage->quantity = $item->quantity;
                $item->companyOrderStorage->save();
                //更新redis库存
                $key = kcGoodsRuleKey() . $item->company_id;
                $quantity = CompanyOrderStorage::gs($item->company_id)->goodsRuleId($item['goods_rule_id'])->sum('quantity');
                redis()->zadd($key, $quantity, $item['goods_rule_id']);
                //更新商品总库存
                $goodsKey = kcGoodsKey() . $item->company_id;
                $quantity = CompanyOrderStorage::gs($item->company_id)->goodsId($item->goods_id)->sum('quantity');
                redis()->zadd($goodsKey, $quantity, $item->goods_id);
            });
        }
        //审核驳回
        if ($model->stock_status == 4 && $model->getOrigin('stock_status') != 2) exception("盘点单状态异常,无法审核驳回");
        if ($model->stock_status == 4) {
            $model->auditor_id   = getCompanyUserId();//审核人
            $model->end_time     = time();//盘点结束时间
            $model->auditor_time = time();//审核时间
        }
    }


    /**
     * 删除前
     * @param WarehouseTakeStock $model
     * @return void
     * @throws DbException
     * @throws Exception
     */
    public static function onBeforeDelete(WarehouseTakeStock $model): void
    {
        if ($model->stock_status == 3) exception("盘点单已通过,无法删除");
        if ($model->warehouseTakeStockGoodss()->count()) {
            $model->warehouseTakeStockGoodss->delete();
        }
    }

}